<template>
  <div class="admin-layout">
    <!-- 左侧菜单 -->
    <div class="sidebar" :class="{ 'sidebar-collapsed': isCollapsed }">
      <div class="logo">
        <h2 v-if="!isCollapsed">万代校园管理</h2>
        <h2 v-else>校园</h2>
      </div>

      <el-menu
        :default-active="$route.path"
        class="sidebar-menu"
        :collapse="isCollapsed"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        router
      >
        <el-menu-item index="/admin/dashboard">
          <i class="el-icon-s-home"></i>
          <span slot="title">仪表盘</span>
        </el-menu-item>

        <el-submenu index="user-management">
          <template slot="title">
            <i class="el-icon-user"></i>
            <span>用户管理</span>
          </template>
          <el-menu-item index="/admin/students">学生管理</el-menu-item>
          <el-menu-item index="/admin/admins">管理员管理</el-menu-item>
        </el-submenu>

        <el-submenu index="tasks">
          <template slot="title">
            <i class="el-icon-tickets"></i>
            <span>任务管理</span>
          </template>
          <el-menu-item index="/admin/labor-types">劳务类型管理</el-menu-item>
          <el-menu-item index="/admin/labors">任务列表</el-menu-item>
        </el-submenu>

        <el-submenu index="second-hand">
          <template slot="title">
            <i class="el-icon-goods"></i>
            <span>二手管理</span>
          </template>
          <el-menu-item index="/admin/second-hand-categories">二手商品类管理</el-menu-item>
          <el-menu-item index="/admin/second-hand-products">二手商品管理</el-menu-item>
        </el-submenu>

        <el-menu-item index="/admin/schools">
          <i class="el-icon-school"></i>
          <span slot="title">学校管理</span>
        </el-menu-item>

        <el-menu-item index="/admin/messages">
          <i class="el-icon-message"></i>
          <span slot="title">消息管理</span>
        </el-menu-item>

        <el-menu-item index="/admin/banners">
          <i class="el-icon-picture"></i>
          <span slot="title">轮播图管理</span>
        </el-menu-item>

        <el-submenu index="system">
          <template slot="title">
            <i class="el-icon-setting"></i>
            <span>系统设置</span>
          </template>
          <el-menu-item index="/admin/settings">系统配置</el-menu-item>
          <el-menu-item index="/admin/logs">操作日志</el-menu-item>
        </el-submenu>
      </el-menu>
    </div>

    <!-- 主内容区域 -->
    <div class="main-content" :class="{ expanded: isCollapsed }">
      <!-- 顶部导航栏 -->
      <div class="header">
        <div class="header-left">
          <el-button
            type="text"
            @click="toggleSidebar"
            class="sidebar-toggle"
            title="切换菜单"
          >
            <i class="el-icon-s-fold" v-if="!isCollapsed"></i>
            <i class="el-icon-s-unfold" v-else></i>
          </el-button>
          <el-button
            type="text"
            @click="resetSidebarState"
            class="sidebar-reset"
            title="重置菜单"
            v-if="isCollapsed"
          >
            <i class="el-icon-refresh"></i>
          </el-button>
          <span class="page-title">{{ currentPageTitle }}</span>
        </div>

        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="admin-info">
              <i class="el-icon-user-solid"></i>
              {{ adminInfo.name || adminInfo.username || '管理员' }}
              <i class="el-icon-arrow-down"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="profile">个人信息</el-dropdown-item>
              <el-dropdown-item command="changePassword">修改密码</el-dropdown-item>
              <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="content-area">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "AdminLayout",
  data() {
    return {
      isCollapsed: false,
      adminInfo: {}
    }
  },
  mounted() {
    // 从localStorage恢复菜单折叠状态
    const savedCollapsed = localStorage.getItem('sidebarCollapsed')
    if (savedCollapsed !== null) {
      this.isCollapsed = JSON.parse(savedCollapsed)
    } else {
      // 如果没有保存的状态，确保菜单是展开的
      this.isCollapsed = false
    }
  },
  watch: {
    // 监听路由变化，确保菜单状态正确
    '$route'() {
      // 路由变化时，确保菜单状态正确显示
      this.$nextTick(() => {
        if (this.isCollapsed) {
          // 如果菜单是折叠状态，确保样式正确应用
          this.$forceUpdate()
        }
      })
    }
  },
  computed: {
    currentPageTitle() {
      const titleMap = {
        "/admin/dashboard": "仪表盘",
        "/admin/students": "学生管理",
        "/admin/admins": "管理员管理",
        "/admin/labor-types": "劳务类型管理",
        "/admin/labors": "任务列表",
        "/admin/errands": "跑腿任务",
        "/admin/substitutes": "代课任务",
        "/admin/express": "快递任务",
        "/admin/second-hand-categories": "二手商品类管理",
        "/admin/second-hand-products": "二手商品管理",
        "/admin/schools": "学校管理",
        "/admin/messages": "消息管理",
        "/admin/banners": "轮播图管理",
        "/admin/settings": "系统配置",
        "/admin/logs": "操作日志"
      }
      return titleMap[this.$route.path] || "仪表盘"
    }
  },
  async created() {
    // 先尝试从localStorage获取管理员信息
    const adminInfo = localStorage.getItem('adminInfo')
    if (adminInfo) {
      try {
        this.adminInfo = JSON.parse(adminInfo)
        this.$store.dispatch("login", this.adminInfo)
      } catch (error) {
        console.error("解析管理员信息失败:", error)
      }
    }

    // 然后尝试从API获取最新信息
    await this.loadAdminInfo()
  },
  methods: {
    toggleSidebar() {
      this.isCollapsed = !this.isCollapsed
      // 保存菜单折叠状态到localStorage
      localStorage.setItem('sidebarCollapsed', JSON.stringify(this.isCollapsed))
    },

    // 重置菜单状态的方法
    resetSidebarState() {
      this.isCollapsed = false
      localStorage.removeItem('sidebarCollapsed')
    },

    handleCommand(command) {
      switch (command) {
        case "profile":
          this.$message.info("个人信息功能开发中")
          break
        case "changePassword":
          this.$message.info("修改密码功能开发中")
          break
        case "logout":
          this.logout()
          break
      }
    },

    async loadAdminInfo() {
      try {
        const response = await this.$http.get("/admin/info")
        if (response.data.code === 200) {
          this.adminInfo = response.data.data
          this.$store.dispatch("login", this.adminInfo)
          // 更新localStorage
          localStorage.setItem('adminInfo', JSON.stringify(this.adminInfo))
        }
      } catch (error) {
        console.error("获取管理员信息失败:", error)
        // 如果API调用失败，使用localStorage中的数据
        if (!this.adminInfo.username) {
          const adminInfo = localStorage.getItem('adminInfo')
          if (adminInfo) {
            try {
              this.adminInfo = JSON.parse(adminInfo)
            } catch (e) {
              console.error("解析localStorage中的管理员信息失败:", e)
            }
          }
        }
      }
    },

    async logout() {
      try {
        await this.$http.post("/admin/logout")
      } catch (error) {
        console.error("退出登录API调用失败:", error)
      } finally {
        localStorage.removeItem("token")
        localStorage.removeItem("adminInfo")
        this.$store.dispatch("logout")
        this.$message.success("退出登录成功")
        this.$router.push("/login")
      }
    }
  }
}
</script>

<style scoped>
.admin-layout {
  display: flex;
  height: 100vh;
  overflow: hidden;
}

/* 左侧菜单 */
.sidebar {
  width: 180px !important;
  min-width: 180px;
  max-width: 180px;
  background-color: #304156;
  overflow: hidden;
  flex-shrink: 0;
}

.sidebar.sidebar-collapsed {
  width: 50px !important;
  min-width: 50px;
  max-width: 50px;
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #2b3a4b;
  color: white;
  margin-bottom: 0;
}

.logo h2 {
  margin: 0;
  font-size: 18px;
  font-weight: bold;
}

.sidebar-menu {
  border: none;
  height: calc(100vh - 60px);
  overflow-y: auto;
  width: 100% !important;
}

.sidebar-menu:not(.el-menu--collapse) {
  width: 100% !important;
}

/* 主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #f0f2f5;
}

.main-content.expanded {
  margin-left: 0;
}

/* 顶部导航栏 */
.header {
  height: 60px;
  background: white;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.header-left {
  display: flex;
  align-items: center;
}

.sidebar-toggle {
  margin-right: 10px;
  font-size: 18px;
}

.sidebar-reset {
  margin-right: 20px;
  font-size: 16px;
  color: #409EFF;
}

.page-title {
  font-size: 18px;
  font-weight: 500;
  color: #333;
}

.header-right {
  display: flex;
  align-items: center;
}

.admin-info {
  cursor: pointer;
  color: #666;
  display: flex;
  align-items: center;
  gap: 8px;
}

.admin-info:hover {
  color: #409EFF;
}

/* 内容区域 */
.content-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}

/* 确保菜单宽度固定 */
.sidebar * {
  box-sizing: border-box;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .sidebar {
    position: fixed;
    left: -250px;
    top: 0;
    height: 100vh;
    z-index: 1000;
    width: 250px !important;
  }

  .sidebar.sidebar-collapsed {
    left: 0;
    width: 64px !important;
  }

  .main-content {
    margin-left: 0;
  }
}
</style>
